package com.xwaf.platform.web.config;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xwaf.platform.web.filter.LockInterceptor;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * <p>
 * Redisson分布式锁
 * <p>
 * 
 * @author 李聪 <br>
 * @email xwaf_love@yeah.net <br>
 * @since JDK 1.8<br>
 * @date 2019年12月30日 上午9:23:26 <br>
 * @see 无<br>
 *      Copyright (c) 2019, xwaf_love@yeah.net All Rights Reserved.<br>
 */
@Slf4j
// @Aspect
// @Component
public class RedisDistributedLockAspect {

	// @Autowired
	// private RedissonClient redissonClient;

	@Pointcut("@annotation(com.xwaf.platform.web.filter.LockInterceptor)")
	private void lockPoint() {
	}

	@Around("lockPoint()")
	public Object around(ProceedingJoinPoint pjp) throws Throwable {
		Class<?> cls = pjp.getTarget().getClass();
		String methodName = pjp.getSignature().getName();
		Class[] parameterTypes = ((MethodSignature) pjp.getSignature()).getMethod().getParameterTypes();
		Method method = cls.getMethod(methodName, parameterTypes);
		LockInterceptor interceptor = method.getAnnotation(LockInterceptor.class);
		String key = interceptor.lockName();
		// RLock lock=getLock(key,interceptor);
		// if(!lock.tryLock(interceptor.waitTime(),interceptor.leaseTime(),interceptor.unit())){
		// log.debug("get lock failed [{}]",key);
		// return null;
		// }
		try {
			return pjp.proceed();
		} catch (Exception e) {
			log.error("execute loked method occured an exception", e);
		} finally {
			// lock.unlock();
		}
		return null;
	}

	// private RLock getLock(String key,LockInterceptor interceptor){
	// switch (interceptor.lockType()){
	// case REENTRANT_LOCK:
	// return redissonClient.getLock(key);
	// case FAIR_LOCK:
	// return redissonClient.getFairLock(key);
	// case READ_LOCK:
	// return redissonClient.getReadWriteLock(key).readLock();
	// case WRITE_LOCK:
	// return redissonClient.getReadWriteLock(key).writeLock();
	// default:
	// throw new RuntimeException("do not support lock type:" +
	// interceptor.lockType().name());
	// }
	// }

}
